package simulation;

import schedule.Schedule;
import timer.Timer;
import constants.Constants;

public class ScheduleRunner implements Runnable {

	private Schedule current;
	private int index;

	private void execute() {
		int next = 0;
		for (int i = Timer.getMinTime(); i < Timer.getMaxTime(); i++) {
			if (next < current.getActionsCount()) {
				if (current.getActions().get(next).getStartTimer() == i) {
					System.out.println("Executing action:"
							+ current.get(next).getOnwer()
							+ transformTime(current.get(next).getStartTimer()));
					current.get(next).execute();

					next++;
				}
			}
			if ((i % Constants.time) == 0) {
				ScheduleProgram.setAccess(index, true);
				while (ScheduleProgram.getAccess(index) != false) {
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

	}

	private String transformTime(int time) {
		int hours = 0, minutes = 0, seconds = 0;
		String timeStr = new String();
		hours = (time / 3600);
		minutes = (time - hours * 3600) / 60;
		seconds = time - hours * 3600 - minutes * 60;
		timeStr = hours + ":" + minutes + ":" + seconds;
		return timeStr;
	}

	public void init(Schedule schedule, int i) {
		index = i;
		current = schedule;
	}

	@Override
	public void run() {
		execute();
		System.out.println("finished " + index);
		ScheduleProgram.setFinished(index, true);
		return;
	}

}
